package com.mzy.datepackage.M2022.July.tentwo;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author mzy
 * @Date 2022/7/16 15:31
 * @Version 1.0
 */
@Slf4j
public class TestThree {

    private static final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
    private static final String myFilePath = "F:\\每日脚本暂存\\新建文件路径\\2022.07.16\\my_iptables.cfg";
    private static final String domainMapIpFilePath = "F:\\每日脚本暂存\\新建文件路径\\2022.07.16\\domainMapIp.conf";
    private static final String test = "F:\\每日脚本暂存\\新建文件路径\\2022.07.16\\test.conf";
    private static final AtomicInteger i = new AtomicInteger();

    public static void main(String[] args) throws IOException {
        File file = new File(domainMapIpFilePath);
        if (!file.exists()) {
            file.createNewFile();
            log.info("创建domainMapIpFilePath");
        }
        File file1 = new File(test);
        if (!file1.exists()) {
            file1.createNewFile();
            log.info("创建test");
        }
        File file2 = new File(myFilePath);
        if (!file2.exists()) {
            file2.createNewFile();
            log.info("创建test");
        }

        executorService.scheduleAtFixedRate(
                () -> {
                    log.info("定时执行Domain处理线程");
                    ArrayList<String> testList = new ArrayList<>();
                    testList.add(i.toString());
                    FileUtilss.writeContent(test, testList, true);
                    i.getAndIncrement();
                    try {
                        // 按行读取IP映射表
                        List<String> read = FileUtilss.readLine(domainMapIpFilePath);

                        System.out.println("能执行到这嘛 1?" + read.size());
                        LinkedHashMap<String, String> stringStringHashMap = new LinkedHashMap<>();
                        read.forEach(e -> {
                            String[] s = e.split("  ");
                            stringStringHashMap.put(s[0], s[1]);
                        });

                        System.out.println("能执行到这嘛2？ " + stringStringHashMap.size());
                        // 检查是否已经改变
                        Boolean isChange = false;
                        // 迭代map，操作
                        for (Map.Entry<String, String> entry :
                                stringStringHashMap.entrySet()
                        ) {
                            // 进入域名解析
                            System.out.println("能执行到这嘛3？ " + entry.getKey() +entry.getValue());

                            String analysisIp = analysis(entry.getKey());
                            // 判断原ip跟当前Ip是否有变更
                            if (entry.getValue().equals(analysisIp)) {
                                continue;
                            } else {

                                // 检查ipTable备份表是否有相同的ip。若有，则变更，并重刷IP tables规则

                                // 修改W ipTables
                                List<String> readLine = FileUtilss.readLine(myFilePath);
                                for (int j = 0; j < readLine.size(); j++) {
                                    if (readLine.get(j).contains(entry.getValue())) {
                                        // 替换旧的Ip为新的Ip
                                        System.out.println(entry.getValue());
                                        System.out.println(analysisIp);
                                        String replace = readLine.get(j).replace(entry.getValue(), analysisIp);
                                        System.out.println(replace);
                                        readLine.set(j, replace);
                                        log.info("域名有变更，执行iptables规则刷新");
                                    }
                                }
                                // 覆盖写入文件
                                FileUtilss.writeContent(myFilePath, readLine, false);
                                // 根据每个域名ip修改W完成
                                // 不相等变更该条ip域名映射，map特性，相同key相同则覆盖
                                stringStringHashMap.put(entry.getKey(), analysisIp);
                                isChange = true;
                            }
                        }

                        // 重刷ipTables规则表
                        ArrayList<String> writeArrays = new ArrayList<>();
                        // 读写一次
                        if (isChange) {
                            log.info("刷新Iptables");
                            stringStringHashMap.forEach((k, v) -> writeArrays.add(k + "  " + v));
                            FileUtilss.writeContent(domainMapIpFilePath, writeArrays, false);
                        }
                    } catch (Exception e) {
                        log.info("定时轮询，域名配置出现问题");
                    }
                }, 0, 10, TimeUnit.SECONDS);
    }



    /**
     * 传入域名，
     * 返回对应ip
     *
     * @param domainName
     * @return
     */
    public static String analysis(String domainName) {
        try {
            InetAddress[] addresses = InetAddress.getAllByName(domainName);
            // 只考虑一个
            System.out.println(domainName + addresses[0].getHostAddress());
            return addresses[0].getHostAddress();
        } catch (UnknownHostException e) {
            log.info("域名解析: {}" + "异常");
            throw new SystemException("域名解析主机异常,请您检查DNS域名服务器是否配置成功");
        }
    }
}
